﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using zPod.zInject;
using System.Reflection;
using Mono.Cecil;
using System.IO;

namespace zInject.CLI
{
    class Program
    {
        const string VerboseError = "-error";

        static void Main(string[] args)
        {
            try
            {
				args = new string[2]
				{
					"CocoaBrowser.exe",
					"CocoaBrowser.exe"
				};

                if (args.Length != 2 && args.Length != 3)
                {
                    throw new Exception("Usage: Inject.CLI <input_assembly_file> <output_assembly_file>");
                }
                else
                {
                    string input = args[0];
                    string output = args[1];

                    if (!File.Exists(input))
                    {
                        throw new Exception("Input file does not exist");
                    }

					AppDomain.CurrentDomain.SetShadowCopyFiles();
                    Injector injector = new Injector();
                    var newAssembly = injector.Inject(input);

					foreach (var method in injector.InjectedMethods)
					{
						Console.WriteLine("Injected: " + method);
					}

                    try
                    {
                        AssemblyFactory.SaveAssembly(newAssembly, output);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Cannot write to output file", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(String.Format("There was an error: {0}", ex.Message));

                if (args.Length == 3 && args[2] == VerboseError)
                {
                    ex = ex.InnerException;
                    while (ex != null)
                    {
                        Console.WriteLine(ex.Message);
                        ex = ex.InnerException;
                    }
                    Console.WriteLine();
                    Console.WriteLine(ex.StackTrace);
                }
            }

        }
    }
}
